package com.lagou.curator;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Stat;

import java.nio.charset.StandardCharsets;
import java.util.List;

public class GetNodeData {

    public static void main(String[] args) throws Exception {
        //不使用 fluent编程风格
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);

        //使用 fluent编程风格
        CuratorFramework client = CuratorFrameworkFactory.builder()
                //zk的server地址，多个server之间使⽤英⽂逗号分隔开
                .connectString("127.0.0.1:2181")
                .sessionTimeoutMs(60 * 1000)
                .connectionTimeoutMs(15 * 1000)
                .retryPolicy(retryPolicy)
                .namespace("base")
                .build();
        client.start();
        System.out.println("会话创建成功。。。");

        //获取权限信息
        List<ACL> aclList = client.getACL().forPath("/lg_curator");
        System.out.println("权限信息为：" + aclList);

        List<String> strings = client.getChildren().forPath("/lg_curator");
        System.out.println("节点信息为：" + strings);

        byte[] data = client.getData().forPath("/lg_curator");
        System.out.println("节点数据为：" + new String(data, StandardCharsets.UTF_8));

        client.getData().usingWatcher(new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                System.out.println("数据更新完成：" + event);
            }
        }).forPath("/lg_curator");

        client.setData().forPath("/lg_curator", "修改".getBytes(StandardCharsets.UTF_8));
        Thread.sleep(1000);
    }

}
